import time

from rest_framework import serializers
from ..models import *
from datetime import datetime


# 生产计划单
class FaKuyouPlanSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouPlan
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 数量验证
        if 'number' in data and data['number'] is not None and data['number'] <= 0:
            raise serializers.ValidationError({'number': '数量必须大于0'})

        # 单价验证
        if 'unit_price' in data and data['unit_price'] is not None and data['unit_price'] < 0:
            raise serializers.ValidationError({'unit_price': '单价不能为负数'})

        # 交货时间不能早于当前时间
        if 'delivery_time' in data and data['delivery_time']:
            now = int(time.time())
            if data['delivery_time'] < now:
                raise serializers.ValidationError({'delivery_time': '交货时间不能早于当前时间'})

        return data


# 生产计划详情单
class FaKuyouPlanInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouPlanInfo
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 数量验证
        if 'number' in data and data['number'] <= 0:
            raise serializers.ValidationError({"number": "数量必须大于0"})

        # 价格验证
        if 'purchase' in data and data['purchase'] < 0:
            raise serializers.ValidationError({"purchase": "进价不能为负数"})

        return data


# MRP计算
class FaKuyouMrpSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouMrp
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 数量验证
        if 'number' in data and data['number'] is not None and data['number'] <= 0:
            raise serializers.ValidationError({"number": "需求数量必须大于0"})

        # 单价验证
        if 'unit_price' in data and data['unit_price'] is not None and data['unit_price'] < 0:
            raise serializers.ValidationError({"unit_price": "单价不能为负数"})

        return data


# MRP计算详情
class FaKuyouMrpInfoSerializer(serializers.ModelSerializer):
    shortage_rate = serializers.SerializerMethodField(help_text='缺货率')

    class Meta:
        model = FaKuyouMrpInfo
        fields = '__all__'

    def get_shortage_rate(self, obj):
        """计算缺货率"""
        if obj.number and obj.number > 0 and obj.stock is not None:
            return round(float(obj.buy_number) / float(obj.number) * 100, 2)
        return 0

    def validate(self, data):
        """数据验证"""
        # 数量验证
        if 'number' in data and data['number'] is not None and data['number'] <= 0:
            raise serializers.ValidationError({"number": "需求数量必须大于0"})

        # 库存验证
        if 'stock' in data and data['stock'] is not None and data['stock'] < 0:
            raise serializers.ValidationError({"stock": "库存数量不能为负数"})

        # 进价验证
        if 'purchase' in data and data['purchase'] is not None and data['purchase'] < 0:
            raise serializers.ValidationError({"purchase": "进价不能为负数"})

        return data


# 生产单
class FaKuyouProductionSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouProduction
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 数量验证
        if 'number' in data and data['number'] is not None and data['number'] <= 0:
            raise serializers.ValidationError({"number": "计划数量必须大于0"})

        # 完成数量不能超过计划数量
        if 'finish_number' in data and data['finish_number'] is not None:
            if data['finish_number'] < 0:
                raise serializers.ValidationError({"finish_number": "完成数量不能为负数"})
            if 'number' in data and data['number'] is not None and data['finish_number'] > data['number']:
                raise serializers.ValidationError({"finish_number": "完成数量不能超过计划数量"})

        # 单价验证
        if 'unit_price' in data and data['unit_price'] is not None and data['unit_price'] < 0:
            raise serializers.ValidationError({"unit_price": "单价不能为负数"})

        return data


# 生产详情单
class FaKuyouProductionInfoSerializer(serializers.ModelSerializer):
    type_display = serializers.CharField(
        source='get_type_display',
        read_only=True,
        help_text='类型显示'
    )
    usage_rate = serializers.SerializerMethodField(
        help_text='使用率(%)'
    )
    create_datetime = serializers.SerializerMethodField(
        help_text='创建时间'
    )
    update_datetime = serializers.SerializerMethodField(
        help_text='更新时间'
    )

    class Meta:
        model = FaKuyouProductionInfo
        fields = '__all__'
        extra_kwargs = {
            'purchase': {'coerce_to_string': False},
            'number': {'coerce_to_string': False},
            'basic_nmber': {'coerce_to_string': False},
            'money': {'coerce_to_string': False},
            'stock_number': {'coerce_to_string': False},
            'need_number': {'coerce_to_string': False},
            'requisition_number': {'coerce_to_string': False},
            'use_number': {'coerce_to_string': False},
            'back_number': {'coerce_to_string': False},
        }

    def get_usage_rate(self, obj):
        return obj.usage_rate

    def get_create_datetime(self, obj):
        if obj.createtime:
            return datetime.fromtimestamp(obj.createtime).strftime('%Y-%m-%d %H:%M:%S')
        return None

    def get_update_datetime(self, obj):
        if obj.updatetime:
            return datetime.fromtimestamp(obj.updatetime).strftime('%Y-%m-%d %H:%M:%S')
        return None

    def validate(self, data):
        """数据验证"""
        # 验证领用数量不超过库存
        if 'requisition_number' in data and 'stock_number' in data:
            if data['requisition_number'] > data['stock_number']:
                raise serializers.ValidationError({
                    'requisition_number': '领用数量不能超过库存数量'
                })

        # 验证使用数量不超过领用数量
        if 'use_number' in data and 'requisition_number' in data:
            if data['use_number'] > data['requisition_number']:
                raise serializers.ValidationError({
                    'use_number': '使用数量不能超过领用数量'
                })

        # 验证退料数量不超过领用数量
        if 'back_number' in data and 'requisition_number' in data:
            if data['back_number'] > data['requisition_number']:
                raise serializers.ValidationError({
                    'back_number': '退料数量不能超过领用数量'
                })

        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret


# 领料单
class FaKuyouPickingSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouPicking
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 数量验证
        if 'number' in data and data['number'] is not None and data['number'] <= 0:
            raise serializers.ValidationError({"number": "领料数量必须大于0"})

        # 实际领用不能超过领料数量
        if 'finish_number' in data and data['finish_number'] is not None:
            if data['finish_number'] < 0:
                raise serializers.ValidationError({"finish_number": "实际领用不能为负数"})
            if 'number' in data and data['number'] is not None and data['finish_number'] > data['number']:
                raise serializers.ValidationError({"finish_number": "实际领用不能超过计划领料数量"})

        # 单价验证
        if 'unit_price' in data and data['unit_price'] is not None and data['unit_price'] < 0:
            raise serializers.ValidationError({"unit_price": "单价不能为负数"})

        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret


# 领料详情单
class FaKuyouPickingInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouPickingInfo
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 验证领用数量不超过库存
        if 'requisition_number' in data and 'stock_number' in data:
            if data['requisition_number'] > data['stock_number']:
                raise serializers.ValidationError({
                    'requisition_number': '领用数量不能超过库存数量'
                })

        # 验证使用数量不超过领用数量
        if 'use_number' in data and 'requisition_number' in data:
            if data['use_number'] > data['requisition_number']:
                raise serializers.ValidationError({
                    'use_number': '使用数量不能超过领用数量'
                })

        # 验证退料数量不超过领用数量
        if 'back_number' in data and 'requisition_number' in data:
            if data['back_number'] > data['requisition_number']:
                raise serializers.ValidationError({
                    'back_number': '退料数量不能超过领用数量'
                })

        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret


# 退料单
class FaKuyouMaterialSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouMaterial
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 数量验证
        if 'number' in data and data['number'] is not None and data['number'] <= 0:
            raise serializers.ValidationError({"number": "退料数量必须大于0"})

        # 实际退料不能超过计划退料
        if 'finish_number' in data and data['finish_number'] is not None:
            if data['finish_number'] < 0:
                raise serializers.ValidationError({"finish_number": "实际退料不能为负数"})
            if 'number' in data and data['number'] is not None and data['finish_number'] > data['number']:
                raise serializers.ValidationError({"finish_number": "实际退料不能超过计划退料数量"})

        # 单价验证
        if 'unit_price' in data and data['unit_price'] is not None and data['unit_price'] < 0:
            raise serializers.ValidationError({"unit_price": "单价不能为负数"})

        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret


# 退料详情单
class FaKuyouMaterialInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouMaterialInfo
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 验证退料数量合理性
        if 'back_number' in data and data['back_number'] is not None:
            if data['back_number'] < 0:
                raise serializers.ValidationError({
                    'back_number': '退料数量不能为负数'
                })
            if 'requisition_number' in data and data['requisition_number'] is not None:
                if data['back_number'] > data['requisition_number']:
                    raise serializers.ValidationError({
                        'back_number': '退料数量不能超过领用数量'
                    })

        # 验证使用数量不超过领用数量
        if 'use_number' in data and 'requisition_number' in data:
            if data['use_number'] > data['requisition_number']:
                raise serializers.ValidationError({
                    'use_number': '使用数量不能超过领用数量'
                })

        # 验证保质期计算
        if 'manufacture' in data and 'guarantee' in data:
            if data['manufacture'] and data['guarantee']:
                data['validity'] = data['manufacture'] + data['guarantee'] * 86400

        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret


# 委外加工单
class FaKuyouOutsourcingSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouOutsourcing
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 数量验证
        if 'number' in data and data['number'] is not None and data['number'] <= 0:
            raise serializers.ValidationError({"number": "委外数量必须大于0"})

        # 完成数量验证
        if 'finish_number' in data and data['finish_number'] is not None:
            if data['finish_number'] < 0:
                raise serializers.ValidationError({"finish_number": "完成数量不能为负数"})
            if 'number' in data and data['number'] is not None and data['finish_number'] > data['number']:
                raise serializers.ValidationError({"finish_number": "完成数量不能超过委外数量"})

        # 单价验证
        if 'unit_price' in data and data['unit_price'] is not None and data['unit_price'] < 0:
            raise serializers.ValidationError({"unit_price": "加工单价不能为负数"})

        # 委外费用验证
        if 'free_money' in data and data['free_money'] is not None and data['free_money'] < 0:
            raise serializers.ValidationError({"free_money": "委外费用不能为负数"})

        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret


# 委外加工详情单
class FaKuyouOutsourcingInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouOutsourcingInfo
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 验证领用数量不超过库存
        if 'requisition_number' in data and 'stock_number' in data:
            if data['requisition_number'] > data['stock_number']:
                raise serializers.ValidationError({
                    'requisition_number': '领用数量不能超过库存数量'
                })

        # 验证使用数量不超过领用数量
        if 'use_number' in data and 'requisition_number' in data:
            if data['use_number'] > data['requisition_number']:
                raise serializers.ValidationError({
                    'use_number': '使用数量不能超过领用数量'
                })

        # 验证退料数量不超过领用数量
        if 'back_number' in data and 'requisition_number' in data:
            if data['back_number'] > data['requisition_number']:
                raise serializers.ValidationError({
                    'back_number': '退料数量不能超过领用数量'
                })

        # 验证保质期计算
        if 'manufacture' in data and 'guarantee' in data:
            if data['manufacture'] and data['guarantee']:
                data['validity'] = data['manufacture'] + data['guarantee'] * 86400

        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret


# 验收单
class FaKuyouAcceptanceSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouAcceptance
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 数量验证
        if 'number' in data and data['number'] is not None and data['number'] <= 0:
            raise serializers.ValidationError({"number": "验收数量必须大于0"})

        # 实际验收不能超过计划验收
        if 'finish_number' in data and data['finish_number'] is not None:
            if data['finish_number'] < 0:
                raise serializers.ValidationError({"finish_number": "实际验收不能为负数"})
            if 'number' in data and data['number'] is not None and data['finish_number'] > data['number']:
                raise serializers.ValidationError({"finish_number": "实际验收不能超过计划验收数量"})

        # 单价验证
        if 'unit_price' in data and data['unit_price'] is not None and data['unit_price'] < 0:
            raise serializers.ValidationError({"unit_price": "单价不能为负数"})

        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret


# 验收详情单
class FaKuyouAcceptanceInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouAcceptanceInfo
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 验证不合格数量
        if 'bad_number' in data and 'number' in data:
            if data['bad_number'] > data['number']:
                raise serializers.ValidationError({
                    'bad_number': '不合格数量不能超过验收数量'
                })

        # 验证验收数量不超过生产数量
        if 'number' in data and 'need_number' in data:
            if data['number'] > data['need_number']:
                raise serializers.ValidationError({
                    'number': '验收数量不能超过生产数量'
                })

        # 验证保质期计算
        if 'manufacture' in data and 'guarantee' in data:
            if data['manufacture'] and data['guarantee']:
                data['validity'] = data['manufacture'] + data['guarantee'] * 86400

        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret
